const path = require('path');
const fs = require('fs');
const combinePath = path.join(process.cwd(), 'uploads');


const combineFile = (dirPath, renameObj) => {
    return new Promise((reslove, reject) => {
        let files = fs.readdirSync(dirPath);
        let currentFilds = files.filter(file => {
            let stats = fs.statSync(path.join(dirPath, file));
            return stats.isFile() && file.startsWith(renameObj.name)
        }).sort((f1, f2) => {
            return f1.slice(-2, -1) - f2.slice(-2, -1);
        });
        let buffers = [];
        currentFilds.forEach(currFile => {
            let buffer = fs.readFileSync(path.join(dirPath, currFile));
            buffers.push(buffer);
        });
        let appendPath = path.join(dirPath, renameObj.filename);
        let concatBuffer = Buffer.concat(buffers);
        fs.writeFileSync(appendPath, concatBuffer);

        currentFilds.forEach((currentFild, index) => {
            fs.unlinkSync(path.join(dirPath, currentFild));
        });
        reslove();
    })
};

// const convertTwo2Ten = (str) => {
//     let arr = str.split('');
//     let sum = 0;
//     let len = arr.length;
//     for (let i = 0; i < len; i++) {
//         let c = len - (i + 1);
//         let item = (2 ** c) * (arr[i] - 0);
//         sum += item;
//     }
//     return sum;
// };
//
// let convert2 = process.argv[2].toString();
// console.log(convertTwo2Ten(convert2))



combineFile(combinePath, {
    filename: "EIE11_ZH-CN_WOL_WIN764.EXE",
    name: "b635b735bbbe2631026d26b719afa92e"
});



